﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fluq;

namespace Fluq
{
	public sealed class DependencyRegistry : IDependencyRegistry
	{
		private IList<IDependency> _dependencies = new List<IDependency>();

		public static IDependencyRegistry FromBuilder(IDependencyBuilder builder)
		{
			if (builder == null)
			{
				throw new ArgumentNullException("builder");
			}

			IDependencyRegistry registry = new DependencyRegistry();

			registry.Add(builder.Dependencies);

			return registry;
		}

		public void Add(IEnumerable<IDependency> dependencies)
		{
			foreach (IDependency dependency in dependencies)
			{
				_dependencies.Add(dependency);
			}
		}

		public IEnumerable<IDependency> Find(IDependencyKey key)
		{
			foreach (IDependency dependency in _dependencies)
			{
				if (Compare(dependency.Key, key) == 0)
				{
					yield return dependency;
				}
			}
		}

		private static int Compare(IDependencyKey x, IDependencyKey y)
		{
			int difference = String.Compare(x.Type.FullName, y.Type.FullName, StringComparison.OrdinalIgnoreCase);

			if (difference == 0)
			{
				IComparable xid = x.Id;
				IComparable yid = y.Id;

				if (xid == null)
				{
					return yid == null ? 0 : 1;
				}
				else
				{
					return xid == null ? -1 : xid.CompareTo(yid);
				}
			}

			return difference;
		}
	}
}
